package net.portly.cst.flex;

import java.util.List;

import net.portly.cst.AssetTypeDescriptor;
import net.portly.cst.MetaAssetContainer;
import net.portly.cst.StructuralAssetInstance;

public class FlexFamily extends MetaAssetContainer {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public AssetTypeDescriptor getFlexDefs() {
		return flexItemsByAssetType.get(FlexItemType.FLEXDEF);
	}
	
	public List<StructuralAssetInstance> getStructuralAssetInstancesForType(FlexItemType flexItem) {
		return structuralAssetMap.get(flexItem);
	}

	public String getFamilyName() {
		String attr = findAssetType(this.getAssetTypeDescriptorForFlexItem(FlexItemType.ATTRIBUTE));
		String parentDef = findAssetType(this.getAssetTypeDescriptorForFlexItem(FlexItemType.PARENTDEF));
		String contentDef = findAssetType(this.getAssetTypeDescriptorForFlexItem(FlexItemType.FLEXDEF));
		
		//* Try _A/_PD/_CD convention first
		String root = null;
		if (attr != null && attr.endsWith("_A")) {
			root = attr.substring(0, attr.length() - 2);
			
			if (parentDef != null) {
				if (!parentDef.startsWith(root + "_")) {
					root = null;
				}
			}
			
			if (contentDef != null && root != null) {
				if (!contentDef.startsWith(root + "_")) {
					root = null;
				}
			}
		}
		
		if (root != null) {
			return root;
		}
		
		return buildDerivedString (attr, parentDef, contentDef);
	}

	private String buildDerivedString(String attr, String parentDef, String contentDef) {
		StringBuilder sb = new StringBuilder();
		
		if (attr != null) {
			sb.append(attr);
			if (parentDef != null || contentDef != null) {
				sb.append("-");
			}
		}
		if (parentDef != null) {
			sb.append(parentDef);
			if (contentDef != null) {
				sb.append("-");
			}
		}
		if (contentDef != null) {
			sb.append(contentDef);
		}
		
		return "derived-" + sb.toString();
	}

	private String findAssetType(AssetTypeDescriptor assetTypeDescriptorForFlexItem) {
		return assetTypeDescriptorForFlexItem != null ? assetTypeDescriptorForFlexItem.getAssettype() : null;
	}
}
